<template>
  <j-modal
    :confirmLoading="confirmLoading"
    :dialogStyle="dialogStyle"
    :title="title"
    :visible="visible"
    :width="1000"
    cancelText="关闭"
    switchFullscreen
    @cancel="handleCancel"
    @ok="handleOk">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="1级分类">
          <a-select v-decorator="['level1Id', {
      rules: [
        {
          required: true,
          message: '1级分类不能为空！',
        },
      ],
    }]"
                    :disabled="isEdit"
                    optionFilterProp="children"
                    placeholder="请选择1级分类"
                    showSearch
          >
            <a-select-opt-group
              v-for="group in formattedOptions"
              :key="group.label"
              :label="group.label"
            >
              <a-select-option
                v-for="option in group.options"
                :key="option.value"
                :value="option.value"
              >
                {{ option.text }}
              </a-select-option>
            </a-select-opt-group>
          </a-select>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="2级分类">
          <a-input v-decorator="['level2', {
           rules: [
              {
                required: true,
               message: '2级分类不能为空！',
              },
            ],
            }]" placeholder="请输入2级分类" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="3级分类">
          <a-input v-decorator="['level3', {
           rules: [
              {
                required: true,
               message: '3级分类不能为空！',
              },
            ],
            }]" placeholder="请输入3级分类" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="上游排放">
          <a-input v-decorator="['upstreamEmissions', {
             rules: [
              {
                required: false,
                message: '仅能输入数字，不能为空！',
                pattern: /^\d+(\.\d+)?$/
              },
            ],
          }]" placeholder="请输入上游排放" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="上游排放单位">
          <a-input v-decorator="['upstreamEmissionsUnit', {}]" placeholder="请输入上游排放单位" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="下游排放">
          <a-input v-decorator="['downstreamEmissions', {
             rules: [
              {
                required: false,
                message: '仅能输入正负整数和0，不能为空！',
                pattern: /^[-+]?\d+$/
              },
            ],
          }]" placeholder="请输入下游排放" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="下游排放单位">
          <a-input v-decorator="['downstreamEmissionsUnit', {}]" placeholder="请输入下游排放单位" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="排放环节">
          <a-input v-decorator="['emissionProcesses', {}]" placeholder="请输入排放环节" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="排放温室气体占比">
          <a-input v-decorator="['ghgPercentage', {}]" placeholder="请输入排放温室气体占比" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="不确定性">
          <a-input v-decorator="['uncertainty', {}]" placeholder="请输入不确定性" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="参考文献/数据来源">
          <a-textarea v-decorator="['dataSource', {}]" :rows="4" placeholder="请输入参考文献/数据来源" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="参考文献/简化">
          <a-input v-decorator="['dataSourceShort', {}]" placeholder="请输入参考文献/简化" />
        </a-form-item>
      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
import pick from 'lodash.pick'
import { httpAction, postAction } from '@api/manage'
import moment from 'moment'

export default {
  name: 'trackModal',
  data() {
    return {
      isEdit: false,
      confirmLoading: false,
      title: '',
      visible: false,
      form: this.$form.createForm(this),
      currentTime: '',
      dialogStyle: {
        top: '100px'
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      list: [],
      url: {
        add: '/carbon/carbonFootprint/add',
        edit: '/carbon/carbonFootprint/edit'
      }
    }
  },
  computed: {
    // 返回已格式化的选项列表，用于在模板的 v-for 中使用
    formattedOptions() {
      const typeNames = ['工业产品', '能源产品', '生活产品', '废弃物处理', '交通服务', '碳汇']
      return this.list.map(group => ({
        label: typeNames[group.type] || `类型 ${group.type}`, // 使用自定义类型名称或默认类型标签
        options: group.list.map(item => ({
          value: item.level1_id,
          text: item.level1.replace(/\n/g, '') // 删除换行符, 使文本适应单行
        }))
      }))
    }
  },
  methods: {
    add() {
      this.edit({})
    },
    edit(record) {
      this.list = JSON.parse(localStorage.getItem('list'))
      console.log(this.list)
      console.log(record)
      this.visible = true
      this.form.resetFields()
      this.model = Object.assign({}, record)
      if (this.model.id) {
        this.isEdit = true
      }
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(
          this.model,
          'level1Id',
          'level2',
          'level3',
          'upstreamEmissions',
          'upstreamEmissionsUnit',
          'downstreamEmissions',
          'downstreamEmissionsUnit',
          'emissionProcesses',
          'ghgPercentage',
          'uncertainty',
          'dataSource',
          'dataSourceShort'
        ))
      })
    },
    handleChange(value) {
      console.log(value)
    },
    close() {
      this.isEdit = false
      this.$emit('close')
      this.visible = false
    },
    handleCancel() {
      this.close()
    },
    handleOk() {
      let that = this
      this.form.validateFields((err, values) => {
        if (!err) {
          let httpurl = ''
          let method = ''
          this.confirmLoading = true
          console.log(this.model)
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          console.log(httpurl)
          let formData = Object.assign(this.model, values)
          httpAction(httpurl, formData, method).then(res => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('refresh')
            } else {
              that.$message.error(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
            that.close()
            this.$emit('loadData')
            that.$parent.$parent.loadData()
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>